package com.bobo.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by bobo on 2016/9/27.
 */
public class UploadFiles {

    private static String PATH = "/public/img/";


    public Map<String, Object[]>  upload(HttpServletRequest request) throws IOException {
        request.setCharacterEncoding("utf-8");
        //为解析类提供配置信息
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //创建解析类的实例
        ServletFileUpload sfu = new ServletFileUpload(factory);
        //开始解析
        sfu.setFileSizeMax(1024 * 10240);
        //每个表单域中数据会封装到一个对应的FileItem对象上

        Map<String, Object[]> map = new HashMap<>();
        String fileName = null;
        try {
            List<FileItem> items = sfu.parseRequest(request);
            //区分表单域
            for (FileItem item : items) {
                //isFormField为true，表示这不是文件上传表单域
                if (!item.isFormField()) {
                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
                    String today =  df.format(new java.util.Date());
                    String path = request.getSession().getServletContext().getRealPath(PATH) + today;
                    File file = new File(path);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    fileName = item.getName();
                    if (fileName == null || "".equals(fileName)) {
                        continue;
                    }
                    fileName = System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
                    file = new File(path + "/" + fileName);
                    if (!file.exists()) {
                        item.write(file);
                        //将上传图片的名字记录到数据库中
                    }
                    map.put(item.getFieldName(), new Object[]{PATH + today + "/" + fileName});
                } else {

                    if (map.containsKey(item.getFieldName())) {
                        Object[] vals = map.get(item.getFieldName());

                        vals = Arrays.copyOf(vals, vals.length + 1);
                        vals[vals.length - 1] = item.getString("utf-8");

                        map.put(item.getFieldName(), vals);

                    } else {
                        map.put(item.getFieldName(), new Object[]{item.getString("utf-8")});



                    }


                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    public void delFile(HttpServletRequest request,  String path) {

        path = request.getSession().getServletContext().getRealPath(path);
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
    }
}
